﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;

namespace ZeroBug.EasyFlow.Core
{
    public class AssemblyHelper
    {
        public Dictionary<string, Type> AssemblyTypes = new();
        public Dictionary<string, string> AssemblyVersion = new();

        public void LoadAssembly(string dllName = "", params string[] dirs)
        {
            string addInDir = AppDomain.CurrentDomain.BaseDirectory;
            AssemblyTypes.Clear();

            foreach (string dir in dirs)
            {
                var UserAssembliesFiles = string.IsNullOrEmpty(dllName) ? Directory.EnumerateFiles(addInDir + $"{dir}", "*.dll") : Directory.EnumerateFiles(addInDir + $"{dir}", $"{dllName}.dll");
                var assemblies = UserAssembliesFiles.Select(file =>
                {
                    try
                    {
                        Assembly.LoadFile(file);
                        return Assembly.LoadFile(file);
                    }
                    catch
                    {
                        return null;
                    }
                });
                foreach (Assembly asb in assemblies)
                {
                    if (asb == null)
                        continue;
                    AssemblyVersion.Add(asb.GetName().Name, asb.GetName().Version.ToString());
                }
                var stepTypes = from assembly in assemblies
                                where assembly != null
                                from t in assembly.ExportedTypes
                                where t.IsClass && !t.IsAbstract
                                select t;
                foreach (Type item in stepTypes)
                {
                    AssemblyTypes.Add(item.Name, item);
                }
            }
        }
        public Dictionary<string, T> GetInstance<T>() where T : class
        {
            Dictionary<string, T> dict = new Dictionary<string, T>();
            foreach (var kvp in AssemblyTypes)
            {
                if(typeof(T).GetTypeInfo().IsAssignableFrom(kvp.Value.GetTypeInfo()))
                {
                    dict.Add(kvp.Key, Activator.CreateInstance(kvp.Value) as T);
                }
            }
            return dict;
        }
    }
}
